<!--
 * @Description: 
 * @Author: your name
 * @version: 
 * @Date: 2024-06-24 09:54:00
 * @LastEditors: your name
 * @LastEditTime: 2024-06-27 14:47:33
-->
<template>
  <a-card title="编辑房户信息" style="width: 600px;pointer-events: all;">
    <template #extra>
      <a-select ref="select" v-model:value="selectBuild" style="width: 120px" :options="buildsOption"
        @change="handleChange"></a-select>
    </template>
    <a-table size="small" bordered :data-source="houseList" :loading="loading" :columns="buildingColumns"
      :pagination="pagination" @change="handlePaginationChange">
      <template #bodyCell="{ column, text, record }">
        <template v-if="['doorNumText', 'floorNumText', 'numberText'].includes(column.dataIndex)">
          <a-tag :color="column.dataIndex === 'doorNumText' ? 'red' : 'green'">{{ text }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a @click="edit(record)">编辑信息</a>
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'positionFix'">
          <div @click="focusOnArea(record)">
            <img style="cursor: pointer;" width="20" height="20" src="/src/assets/position.png" alt="">
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <FormInfo :formData="formData" :formOpen="formOpen" @onClose="onClose"/>
</template>

<script setup>
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
import { getBuild, getHouse,getOneHouseInfo } from '@/api/api'
import { ref, onMounted, reactive,onBeforeUnmount } from 'vue'
import FormInfo from './FormInfo.vue'
import { useMapData } from '@/store'

const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const selectBuild = ref('')
const buildsOption = ref([])
const formData=ref({})
const formOpen=ref(false)
const loading = ref(false)
const currentBuild=ref(null)
const pagination = reactive({
  total: 0,
  current: 0,
  pageSize: 0
})

const buildingColumns = ref([
  {
    title: '门牌号',
    dataIndex: 'doorNumText',
    align: 'center',
    ellipsis: true
  }, {
    title: '单元号',
    dataIndex: 'numberText',
    align: 'center',
    ellipsis: true
  }, {
    title: '楼层',
    dataIndex: 'floorNumText',
    align: 'center',
    ellipsis: true
  }, {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    ellipsis: true
  }, {
    title: '定位',
    dataIndex: 'positionFix',
    align: 'center',
    width: '10%'
  }
])

// 楼栋信息
const houseList = ref([])
// 当前渲染的图元
let primitiveHouse
let currentBuildEnt
onMounted(async () => {
  const buildInfo = await getBuild()
  if (buildInfo?.code === 200) {
    buildsOption.value = buildInfo.data.map(item => {
      return {
        value: item.id,
        label: item.name,
        polygon: item.polygon
      }
    })
  }
})

onBeforeUnmount(()=>{
  primitiveHouse && viewer.scene.primitives.remove(primitiveHouse);
  currentBuildEnt && viewer.entities.remove(currentBuildEnt)
  currentBuildEnt = null
  primitiveHouse = null
})

// 选中楼栋。渲染表格，并在地图上添加实体，展示楼栋
const handleChange =(e) => {
  primitiveHouse && viewer.scene.primitives.remove(primitiveHouse);
  currentBuildEnt && viewer.entities.remove(currentBuildEnt)
  currentBuildEnt = null
  primitiveHouse = null
  // 渲染entity，包裹楼栋
  const target = buildsOption.value.find(item => item.value === e)
  if (target) {
    const { polygon } = target
    const center = turf.center(polygon)
    const coordinates = polygon.coordinates[0].reduce((a, b) => a.concat(b), [])
    currentBuildEnt = viewer.entities.add({
      name: target.label,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(
          new Cesium.Cartesian3.fromDegreesArray(coordinates)
        ),
        material: Cesium.Color.RED.withAlpha(0.6),
        classificationType: Cesium.ClassificationType.BOTH
      }
    })

    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        ...center.geometry.coordinates,
        200
      ),
    });
    currentBuild.value=e
    const queryParam = {
      id: e,
      pageIndex: 1
    }
    getHouseData(queryParam)
  }
}

const getHouseData = async (param) => {
  loading.value = true
  const res = await getHouse(param)
  console.log(res);
  if (res.code == 200) {
    houseList.value = res.data.list.map(item => {
      // 构造门牌号
      const doorNumText = `${item.floorNum}-0${item.number}`
      // 构造单元号
      const numberText = `${item.number}单元`
      // 构造楼层
      const floorNumText = `${item.floorNum}楼`
      return {
        ...item,
        doorNumText,
        numberText,
        floorNumText
      }
    });
    pagination.total = res.data.total
    pagination.pageSize = houseList.value.length
    pagination.current = param.pageIndex
  }
  loading.value = false
}

const focusOnArea = (record) => {
  console.log(record);
  primitiveHouse && viewer.scene.primitives.remove(primitiveHouse);
  if (record) {
    const { polygon, minHeight, maxHeight } = record
    const coordinates = polygon.coordinates[0].reduce((a, b) => a.concat(b), [])
    primitiveHouse = new Cesium.ClassificationPrimitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.PolygonGeometry({
          polygonHierarchy: new Cesium.PolygonHierarchy(
            Cesium.Cartesian3.fromDegreesArray(coordinates)
          ),
          height: minHeight,
          extrudedHeight: maxHeight,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(
            Cesium.Color.YELLOW.withAlpha(0.8)
          ),
        },
      }),
      classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
    });
    viewer.scene.primitives.add(primitiveHouse)
  }
}

const edit =async (data) => {
  const {id,number,floorNum}=data
  const res=await getOneHouseInfo({id})
  if(res?.code===200){
    formOpen.value=true
    let houseNum = number > 9 ? number : "0" + number;
    const houseAddress =number + "单元" + floorNum + houseNum;
    res.data.houseAddress=houseAddress
    res.data.id=id
    formData.value=res.data
  }
}

const onClose=()=>{
  formOpen.value=false
}

const handlePaginationChange=(pagination)=>{
  const {current}=pagination
  const queryParam = {
      id: currentBuild.value,
      pageIndex: current
  }
  getHouseData(queryParam)
}

</script>
<style scoped lang='less'></style>